package ${scfg._web_pkg};

import ${scfg._api_pkg}.I${tcfg.tableNameFormat!}Service;
import ${scfg._dto_pkg}.${tcfg.tableNameFormat!}Dto;
import ${scfg._fxml_java_pkg}.*;

import cn.wu.controller.BaseController;
import cn.wu.framework.PageDto;
import cn.wu.framework.annotation.auth.Logical;
import cn.wu.framework.annotation.auth.RequiresPermissions;
import cn.wu.framework.dto.FXMLValidDto;
import cn.wu.framework.util.CommonConstant;
import cn.wu.view.DataButtonCell;
import cn.wu.view.DataTableCell;
import cn.wu.view.PageBar;
import cn.wu.view.SeqlTableCell;
import de.felixroske.jfxsupport.FXMLController;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URL;
import java.time.format.DateTimeFormatter;
import java.util.ResourceBundle;

@FXMLController
@Slf4j
@[if(validator.notEmpty(tcfg.tableComment)){/]/** <p> ${tcfg.tableComment} */@[ } /]
public class FX${tcfg.tableNameFormat!}Controller extends BaseController implements Initializable  {
    //${strUtil.containsStr(tcfg.tableName,'_vs_')?' ':''}INSERT INTO `auth_perm` (id,name,match_str,parent_id,memo,order_no,del_flag) VALUES ('id_${tcfg.tableName}', '${tcfg.tableComment}', '${tableNameL}:menu', 'id_${tcfg.schemaConf._my_pkg}', '系统生成', '0','0');
    //${strUtil.containsStr(tcfg.tableName,'_vs_')?'-- ':''}INSERT INTO `auth_perm` (id,name,match_str,parent_id,memo,order_no,del_flag) VALUES ('id_${tcfg.tableName}_add', '${tcfg.tableComment}_新增', '${tableNameL}:add', 'id_${tcfg.tableName}', '系统生成', '0','0');
    //${strUtil.containsStr(tcfg.tableName,'_vs_')?'-- ':''}INSERT INTO `auth_perm` (id,name,match_str,parent_id,memo,order_no,del_flag) VALUES ('id_${tcfg.tableName}_edit', '${tcfg.tableComment}_编辑', '${tableNameL}:edit', 'id_${tcfg.tableName}', '系统生成', '0','0');
    //${strUtil.containsStr(tcfg.tableName,'_vs_')?'-- ':''}INSERT INTO `auth_perm` (id,name,match_str,parent_id,memo,order_no,del_flag) VALUES ('id_${tcfg.tableName}_info', '${tcfg.tableComment}_详情', '${tableNameL}:info', 'id_${tcfg.tableName}', '系统生成', '0','0');
    @[ if ("1"==scfg._delLogic && null!=scfg._col_del) { /]
    //${strUtil.containsStr(tcfg.tableName,'_vs_')?'-- ':''}INSERT INTO `auth_perm` (id,name,match_str,parent_id,memo,order_no,del_flag) VALUES ('id_${tcfg.tableName}_del', '${tcfg.tableComment}_逻辑删除', '${tableNameL}:del', 'id_${tcfg.tableName}', '系统生成', '0','0');
    @[ }
    if ("1"==scfg._del) { /]
    //INSERT INTO `auth_perm` (id,name,match_str,parent_id,memo,order_no,del_flag) VALUES ('id_${tcfg.tableName}_phydel', '${tcfg.tableComment}_物理删除', '${tableNameL}:phydel', 'id_${tcfg.tableName}', '系统生成', '0','0');
    @[ } /]
    //--  INSERT INTO `auth_perm` (id,name,match_str,parent_id,memo,order_no,del_flag) VALUES ('id_${tcfg.tableName}_recycle', '${tcfg.tableComment}_回收站', '${tableNameL}:recycle', 'id_${tcfg.tableName}', '系统生成', '0','0');
    //--  INSERT INTO `auth_perm` (id,name,match_str,parent_id,memo,order_no,del_flag) VALUES ('id_${tcfg.tableName}_recovery', '${tcfg.tableComment}_回收站_恢复', '${tableNameL}:recovery', 'id_${tcfg.tableName}', '系统生成', '0','0');

    private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    @Autowired
    private I${tcfg.tableNameFormat!}Service ${tableNameL}Service;
    @FXML
    private BorderPane ${tableNameL}Pane;
    @Autowired
    private ${tcfg.tableNameFormat!}View ${tableNameL}View;
    //页码
    private Integer pageNum;
    @FXML
    private FlowPane pageBar;
    @FXML
    private DatePicker dateBeginInput;
    @FXML
    private DatePicker dateEndInput;
    @FXML
    private TextField keywordInput;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        log.info("initialize...");
        pageNum=1;
        loadPage();
    }

    @FXML
    private TableView<${tcfg.tableNameFormat!}Dto> dataTableView;
    @FXML
    private TableColumn seqTableColumn@[ for( t in scfg._col_show!){ /],${t.key!}TableColumn@[}/],operTableColumn;

    /**
     * <p> 信息分页 (未删除)。
     */
    //@RequiresPermissions("${tableNameL}:page")
    @FXML
    public void loadPage() {
        log.info("loadPage.........");
        try {
            ObservableList<${tcfg.tableNameFormat!}Dto> dataList = FXCollections.observableArrayList();
            ${tcfg.tableNameFormat!}Dto dto = new ${tcfg.tableNameFormat!}Dto();
            dto.setPageSize(CommonConstant.PAGEROW_DEFAULT_COUNT);
            dto.setPageNum(pageNum);
            if (dateBeginInput.getValue() != null) {
                dto.setDateBegin(dateBeginInput.getValue().format(dateTimeFormatter));
            }
            if (dateEndInput.getValue() != null) {
                dto.setDateEnd(dateEndInput.getValue().format(dateTimeFormatter));
            }
            dto.setKeyword(keywordInput.getText());

            PageDto pageDto = getPageDto(${tableNameL}Service.findDataIsPage(dto));
            dataList.addAll(pageDto.getData());
            dataTableView.setItems(dataList);
            seqTableColumn.setCellFactory((col) -> new SeqlTableCell());
            @[ for( t in scfg._col_show!){ /]
            //${t.value!}
            ${t.key!}TableColumn.setCellFactory((col) -> new DataTableCell("${t.key!}"));
            @[}/]
            //操作
            operTableColumn.setCellFactory((col) -> new ButtonCell(dataTableView));

            pageBar.getChildren().setAll(new PageBar(this, pageDto, "loadPage").getBar());
        } catch (Exception e) {
            log.error("系统异常!",e);
            AlertView.error(e.getMessage());
        }
    }

    @[ if ("1"==scfg._insert||"1"==scfg._update) { /]
    @FXML
    private BorderPane ${tableNameL}EditPane;
    private FXMLValidDto<${tcfg.tableNameFormat!}Dto> validDto;
    /**
     * <p> 信息保存
     */
    @RequiresPermissions(value = {"${tableNameL}:add", "${tableNameL}:edit"}, logical = Logical.OR)
    @FXML
    public void save() {
        log.info("save.........");
        try {
            ${tcfg.tableNameFormat!}Dto dto = new ${tcfg.tableNameFormat!}Dto();
            validDto = FXMLValidDto.validateBuilder(${tableNameL}EditPane,dto);
            //jsr303Check(dto);
            if(validDto.isValid){
                ${tableNameL}Service.saveOrUpdateData(dto);
                cancel();
                loadPage();
                AlertView.success("操作成功!");
            }
        } catch (Exception e) {
            log.error("系统异常:", e);
            AlertView.error(e.getMessage());
        }
    }

    @Autowired
    private ${tcfg.tableNameFormat!}EditView ${tableNameL}EditView;
    @FXML
    public void edit() {
        log.info("edit.........");
        clearEditView();
        idialog.openDialog("${tcfg.tableComment}-编辑", ${tableNameL}EditView, 800.0, 680.0);
    }

    private void edit(${tcfg.tableNameFormat!}Dto dto) {
        log.info("edit.........");
        try{
            clearEditView();
            if (dto != null) {
            @[ for( t in beanVo!){ /]
                @[if(scfg._edit_type[t.columnNameFormat]!=null){/]
                FXMLValidDto.setNodeValue(${tableNameL}EditPane,"${t.columnNameFormat}Input",dto.get${strUtil.toUpperCaseFirstOne(t.columnNameFormat)}()${t.javaType=='Date'?',"yyyy-MM-dd"':''});//${t.columnComment!}
                @[ } /]
            @[ } /]
            }
        } catch (Exception e) {
            log.error("系统异常:", e);
            AlertView.error(e.getMessage());
        }
    }
    @[}/]

    @[ if ("1"==scfg._detail) { /]
    @Autowired
    private ${tcfg.tableNameFormat!}InfoView ${tableNameL}InfoView;

    @FXML
    private BorderPane ${tableNameL}InfoPane;
    private void info(${tcfg.tableNameFormat!}Dto dto) {
        log.info("info.........");
        try{
            clearInfoView();
            if (dto != null) {
                @[ for( t in beanVo!){ /]
                FXMLValidDto.setNodeValue(${tableNameL}InfoPane,"${t.columnNameFormat}Output",dto.get${strUtil.toUpperCaseFirstOne(t.columnNameFormat)}()${t.javaType=='Date'?',"yyyy-MM-dd HH:mm:ss"':''});//${t.columnComment!}
                @[ } /]
            }
        } catch (Exception e) {
            log.error("系统异常:", e);
            AlertView.error(e.getMessage());
        }
    }
    @[}/]

    @FXML
    public void cancel() {
        log.info("cancel.........");
        @[ if ("1"==scfg._insert||"1"==scfg._update) { /]
        if(${tableNameL}EditView!=null && idialog.getStage(${tableNameL}EditView)!=null) {
            idialog.getStage(${tableNameL}EditView).hide();
        }
        @[}/]
        @[ if ("1"==scfg._detail) { /]
        if(${tableNameL}InfoView!=null && idialog.getStage(${tableNameL}InfoView)!=null) {
            idialog.getStage(${tableNameL}InfoView).hide();
        }
        @[}/]
    }

    @FXML
    public void clearEditView() {
        String[] nodeIdArr = new String[]{
        @[ for( t in beanVo!){if(scfg._edit_type[t.columnNameFormat]!=null){/],"${t.columnNameFormat}Input"@[}}/]
        };
        for (String nodeId : nodeIdArr) {
            FXMLValidDto.setNodeValue(${tableNameL}EditPane, nodeId, null);
        }
    }

    private final String[] infoPaneNodeIdArr = new String[]{
    @[ for( t in beanVo!){/],"${t.columnNameFormat}Output"@[}/]
    };
    @FXML
    public void clearInfoView() {
        for (String nodeId : infoPaneNodeIdArr) {
            FXMLValidDto.setNodeValue(${tableNameL}InfoPane, nodeId, null);
        }
    }

    @FXML
    public void resetSearch() {
        log.info("resetSearch.........");
        dateBeginInput.setValue(null);
        dateEndInput.setValue(null);
        keywordInput.setText(null);
    }

    @[ if ("1"==scfg._delLogic && null!=scfg._col_del || "1"==scfg._del) { /]
    /**
     * <li>删除。
     */
    @RequiresPermissions("${tableNameL}:del")
    private void del(long id) {
        log.info("del.........");
        try {
            ${tcfg.tableNameFormat!}Dto dto = new ${tcfg.tableNameFormat!}Dto();
            dto.setId(id);
            ${tableNameL}Service.deleteData(dto);
            loadPage();
            AlertView.success("操作成功!");
        } catch (Exception e) {
            log.error("系统异常:", e);
            AlertView.error(e.getMessage());
        }
    }
    @[}/]

    @Override
    public void dispose() {}

    class ButtonCell<T> extends DataButtonCell {
        public ButtonCell(final TableView table) {
            @[ if ("1"==scfg._detail) { /]
            if (jwtUtil.hasPermission("${tableNameL}:info")) {
                Node node=getNodeBtn("详情","text-info");
                node.setOnMouseClicked((m) -> {
                    log.debug("OperCell...info...");
                    ${tcfg.tableNameFormat!}Dto dto = (${tcfg.tableNameFormat!}Dto) table.getSelectionModel().getSelectedItem();
                    idialog.openDialog("${tcfg.tableComment}-详情", ${tableNameL}InfoView, 800.0, 680.0,false,false);
                    info(dto);
                });
                paddedButton.getChildren().add(node);
            }
            @[}/]

            @[ if ("1"==scfg._update) { /]
            if (jwtUtil.hasPermission("${tableNameL}:edit")) {
                Node node=getNodeBtn("编辑","text-success");
                node.setOnMouseClicked((m) -> {
                    log.debug("OperCell...edit...");
                    ${tcfg.tableNameFormat!}Dto dto = (${tcfg.tableNameFormat!}Dto) table.getSelectionModel().getSelectedItem();
                    idialog.openDialog("${tcfg.tableComment}-编辑", ${tableNameL}EditView, 800.0, 680.0,false,false);
                    edit(dto);
                });
                paddedButton.getChildren().add(node);
            }
            @[}/]

            @[ if ("1"==scfg._delLogic && null!=scfg._col_del || "1"==scfg._del) { /]
            if (jwtUtil.hasPermission("${tableNameL}:del")) {
                Node node=getNodeBtn("删除","text-danger");
                node.setOnMouseClicked((m) -> {
                    log.debug("OperCell...del...");
                    if(AlertView.confirm("是否删除,此操作不可恢复!")){
                        ${tcfg.tableNameFormat!}Dto dto = (${tcfg.tableNameFormat!}Dto) table.getSelectionModel().getSelectedItem();
                        del(dto.getId());
                    }
                });
                paddedButton.getChildren().add(node);
            }
            @[}/]
        }
    }
}